<?php

use TencentCloud\Common\Credential;
use TencentCloud\Common\Profile\ClientProfile;
use TencentCloud\Common\Profile\HttpProfile;
use TencentCloud\Iai\V20200303\IaiClient;
use TencentCloud\Iai\V20200303\Models\SearchFacesRequest;
use TencentCloud\Iai\V20200303\Models\CreatePersonRequest;
use TencentCloud\Common\Exception\TencentCloudSDKException;

class Tencentcloud
{
    private $secretid = "AKIDQZ9qJXZp7D1A2enozrVt0sc7Pccair7H";//id
    private $secretkey = "LFuSs35rNfOxiJeMlV2ZstfB5i4FEAtB";//秘钥
    private $region = "ap-chengdu";//区域
    private $groupIds = "yssd";//人员库id

    public function searchFaces($url)
    {
        try {
            $cred = new Credential($this->secretid, $this->secretkey);
            $httpProfile = new HttpProfile();
            $httpProfile->setEndpoint("iai.tencentcloudapi.com");
            $clientProfile = new ClientProfile();
            $clientProfile->setHttpProfile($httpProfile);
            $client = new IaiClient($cred, $this->region, $clientProfile);
            $req = new SearchFacesRequest();
            $params = array(
                "GroupIds" => array($this->groupIds),
                "Url" => $url
            );
            $req->fromJsonString(json_encode($params));
            $resp = $client->SearchFaces($req);
            $result = objectToArray($resp);
            if ($result['Results'][0]['Candidates'][0]['Score'] > 80) {
                return ['code' => 1, 'message' => 'ok', 'mobile' => $result['Results'][0]['Candidates'][0]['PersonId']];
            }
            return ['code' => 0, 'message' => '认证失败'];
        } catch (TencentCloudSDKException $e) {
            return ['code' => $e->getCode(), 'message' => $e->getMessage()];
        }
    }

    public function createPerson($name, $mobile, $url)
    {
        try {
            $cred = new Credential($this->secretid, $this->secretkey);
            $httpProfile = new HttpProfile();
            $httpProfile->setEndpoint("iai.tencentcloudapi.com");
            $clientProfile = new ClientProfile();
            $clientProfile->setHttpProfile($httpProfile);
            $client = new IaiClient($cred, $this->region, $clientProfile);
            $req = new CreatePersonRequest();
            $params = array(
                "GroupId" => $this->groupIds,
                "PersonName" => $name,
                "PersonId" => $mobile,
                "Url" => $url
            );
            $req->fromJsonString(json_encode($params));
            $resp = $client->CreatePerson($req);
            $type = gettype($resp);
            if ($type == "object") {
                return objectToArray($resp);
            }
        } catch (TencentCloudSDKException $e) {
            return ['FaceId' => ''];
        }
    }
}
